<template>
    <div id="form" class="py-4 px-6">
        <a-page-header :title="title" @back="back" class="mb-6" />

        <a-form ref="FormRef" :model="formState" v-bind="$attrs">
            <template v-for="formItem in getFormList" :key="formItem.label">
                <a-form-item-rest v-if="formItem.type === 'free'">
                    <div class="mb-8">
                        <div class="mb-2">{{ formItem.label + ' : ' }}</div>
                        <div class="mb-5 text-gray-500">{{ formItem.tip }}</div>
                        <div class="flex items-end w-[600px] mb-6"
                            v-for="(_, index) in formItem.children ? formItem.children : 1" :key="_.id">
                            <a-input v-if="_.type === 'input'" v-model:value="formState[formItem.key][index]"
                                :placeholder="`请输入${formItem.label}`"></a-input>

                            <div class="flex" v-if="_.type === 'range'">
                                <div>
                                    <div class="mb-2">时间范围(分钟) : </div>
                                    <a-input-number class="w-24"
                                        v-model:value="formState[formItem.key][index].startTime" :min="0" :max="100"
                                        :step="1" :placeholder="`请输入${formItem.label}`" />
                                    &nbsp;~&nbsp;
                                    <a-input-number class="w-24" v-model:value="formState[formItem.key][index].endTime"
                                        :min="0" :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                                <div class="ml-5">
                                    <div class="mb-2">超时费用比例 : </div>
                                    <a-input-number v-model:value="formState[formItem.key][index].fee" :min="0"
                                        :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                            </div>

                            <div v-if="_.type === 'distanceRule'" class="flex">
                                <div>
                                    <div class="mb-2">范围(km)</div>
                                    <a-input-number class="w-24"
                                        v-model:value="formState[formItem.key][index].startDistance" :min="0" :max="100"
                                        :step="1" :placeholder="`请输入${formItem.label}`" />
                                    &nbsp;~&nbsp;
                                    <a-input-number class="w-24"
                                        v-model:value="formState[formItem.key][index].endDistance" :min="0" :max="100"
                                        :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                                <div class="ml-5">
                                    <div class="mb-2">距离单位 : </div>
                                    <a-input-number v-model:value="formState[formItem.key][index].fee" :min="0"
                                        :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                                <div class="ml-5">
                                    <div class="mb-2">价格(元) : </div>
                                    <a-input-number v-model:value="formState[formItem.key][index].fee" :min="0"
                                        :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                            </div>
                            <div v-if="_.type === 'weightRules'" class="flex">
                                <div>
                                    <div class="mb-2">范围(kg)</div>
                                    <a-input-number class="w-24"
                                        v-model:value="formState[formItem.key][index].startDistance" :min="0" :max="100"
                                        :step="1" :placeholder="`请输入${formItem.label}`" />
                                    &nbsp;~&nbsp;
                                    <a-input-number class="w-24"
                                        v-model:value="formState[formItem.key][index].endDistance" :min="0" :max="100"
                                        :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                                <div class="ml-5">
                                    <div class="mb-2">重量单位 : </div>
                                    <a-input-number v-model:value="formState[formItem.key][index].weight" :min="0"
                                        :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                                <div class="ml-5">
                                    <div class="mb-2">价格(元) : </div>
                                    <a-input-number v-model:value="formState[formItem.key][index].fee" :min="0"
                                        :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                            </div>
                            <div v-if="_.type === 'timePeriodRules'" class="flex">
                                <div>
                                    <div class="mb-2">范围(kg)</div>
                                    <a-time-picker class="w-24"
                                        v-model:value="formState[formItem.key][index].startTime" />
                                    &nbsp;~&nbsp;
                                    <a-time-picker class="w-24"
                                        v-model:value="formState[formItem.key][index].endTime" />
                                </div>
                                <div class="ml-5">
                                    <div class="mb-2">价格(元) : </div>
                                    <a-input-number v-model:value="formState[formItem.key][index].fee" :min="0"
                                        :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                            </div>

                            <div v-if="_.type === 'weightLabel'" class="flex">
                                <div>
                                    <div class="mb-2">标签名称</div>
                                    <a-input class="w-32" v-model:value="formState[formItem.key][index].name"
                                        placeholder="请输入标签" />
                                </div>
                                <div class="ml-5">
                                    <div class="mb-2">
                                        取值: &nbsp;
                                        <a-radio-group v-model:value="formState[formItem.key][index].state"
                                            name="radioGroup">
                                            <a-radio value="1">值</a-radio>
                                            <a-radio value="2">范围</a-radio>
                                        </a-radio-group>
                                    </div>
                                    <a-input-number class="w-24" v-model:value="formState[formItem.key][index].start"
                                        :min="0" :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                    &nbsp;~&nbsp;
                                    <a-input-number class="w-24" v-model:value="formState[formItem.key][index].end"
                                        :min="0" :max="100" :step="1" :placeholder="`请输入${formItem.label}`" />
                                </div>
                            </div>

                            <div v-if="_.type === 'discountCouponRules'">
                                <div class="flex">
                                    <div>
                                        <div class="mb-2">选择一张优惠卷</div>
                                        <a-select class="w-40" v-model:value="formState[formItem.key].coupon"
                                            placeholder="请选择优惠卷">
                                            <a-select-option v-for="item in formState[formItem.key].options"
                                                :key="item.value" :value="item.value">{{ item.label
                                                }}</a-select-option>
                                        </a-select>
                                    </div>
                                    <div class="ml-5">
                                        <div class="mb-2">概率(填100标识100%获得)</div>
                                        <a-input class="w-40" v-model:value="formState[formItem.key].probability" />
                                    </div>
                                </div>
                            </div>

                            <div @click="removeFormItem(formItem, index)"
                                class="ml-5 w-8 h-8 text-white rounded-full bg-red-500 flex-center">
                                <DeleteOutlined />
                            </div>
                        </div>
                        <a-button @click="addFormItem(formItem)" type="primary" ghost size="large"
                            :icon="h(PlusCircleOutlined)">添加一项</a-button>
                    </div>
                </a-form-item-rest>
                <a-form-item-rest v-else-if="formItem.type === 'drawSome'">
                    <div class="mb-8">
                        <div class="mb-2">{{ formItem.label + ' : ' }}</div>
                        <div class="flex mb-4">
                            <div>
                                <div class="mb-2">帮我送</div>
                                <a-input-number class="w-24" v-model:value="formState[formItem.key].helpMeDeliverIt"
                                    :min="0" :max="1" :step="0.01"
                                    :placeholder="formState[formItem.key].helpMeDeliverIt" />
                            </div>
                            <div class="ml-5">
                                <div class="mb-2">帮我取</div>
                                <a-input-number class="w-24" v-model:value="formState[formItem.key].helpMeRetrieveIt"
                                    :min="0" :max="1" :step="0.01" />
                            </div>
                            <div class="ml-5">
                                <div class="mb-2">帮我买</div>
                                <a-input-number class="w-24" v-model:value="formState[formItem.key].helpMeBuyIt"
                                    :min="0" :max="1" :step="0.01" />
                            </div>
                        </div>
                        <div class="text-gray-500">{{ formItem.tip }}</div>
                    </div>
                </a-form-item-rest>
                <a-form-item-rest v-else-if="formItem.type === 'discount'">
                    <div class="mb-8">
                        <div class="flex mb-4">
                            <div>
                                <div class="mb-2">优惠金额</div>
                                <a-input class="w-40" v-model:value="formState[formItem.key].discountAmount"
                                    :placeholder="formState[formItem.key].helpMeDeliverIt" />
                            </div>
                            <div class="ml-5">
                                <div class="mb-2">满足条件金额</div>
                                <a-input class="w-40" v-model:value="formState[formItem.key].qualifiedAmount" />
                            </div>
                        </div>
                        <div class="text-gray-500">{{ formItem.tip }}</div>
                    </div>
                </a-form-item-rest>
                <a-form-item v-else="formItem.key" v-bind="formItem">
                    <a-input @change="change(formItem)" v-if="formItem.type === 'input'"
                        v-model:value="formState[formItem.key]" :placeholder="`请输入${formItem.label}`" />

                    <a-select @change="change(formItem)" v-if="formItem.type === 'select'"
                        v-model:value="formState[formItem.key]" :placeholder="`请输入${formItem.label}`" defaultActiveFirstOption>
                        <a-select-option v-for="option in formItem.options" :key="option.value">{{ option.label
                            }}</a-select-option>
                    </a-select>

                    <a-radio-group @change="change(formItem)" v-if="formItem.type === 'radio'"
                        v-model:value="formState[formItem.key]" :name="formItem.key">
                        <a-radio v-for="option in formItem.options" :key="option.label" :value="option.value">{{
                            option.label }}</a-radio>
                    </a-radio-group>

                    <a-checkbox @change="change(formItem)" v-if="formItem.type === 'checkbox'"
                        v-model:checked="formState[formItem.key]"></a-checkbox>

                    <a-checkbox-group @change="change(formItem)" v-if="formItem.type === 'checkGroup'"
                        v-model:value="formState[formItem.key]" :name="formItem.label" :options="formItem.options" />

                    <a-button @click.prevent="onSubmit" v-if="formItem.type === 'submit'" type="primary"
                        html-type="submit" size="large">{{
                            formItem.value }}</a-button>

                    <div v-if="formItem.type === 'upload'">
                        <a-upload v-model:file-list="formState[formItem.key]"
                            name="avatar" list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
                            action="" @change="change(formItem)">
                            <img v-if="formState[formItem.key] && formState[formItem.key].length > 0"
                                :src="formState[formItem.key]" alt="avatar" />
                            <div v-else>
                                <!-- <loading-outlined v-if="loading"></loading-outlined> -->
                                <plus-outlined></plus-outlined>
                                <div class="ant-upload-text">上传</div>
                            </div>
                        </a-upload>
                        <div class="text-gray-400 text-sm mb-4">上传格式:jpg,jpeg,png</div>
                    </div>

                    <a-cascader @change="change(formItem)" v-if="formItem.type === 'cascader'"
                        v-model:value="formState[formItem.key]" :options="formItem.options"
                        :placeholder="`请输入${formItem.label}`" />

                    <a-input-number class="w-24" @change="change(formItem)" v-model:value="formState[formItem.key]"
                        v-if="formItem.type === 'number'"></a-input-number>
                </a-form-item>
            </template>
        </a-form>
    </div>
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash-es';
import { CustomFormItem, CustomFormProps, CustomFormState } from './types';
import { message } from 'ant-design-vue';
import { h } from 'vue'
import { PlusCircleOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { nanoid } from 'nanoid';
import dayjs, { Dayjs } from 'dayjs';
import { ref, watch } from 'vue';

const router = useRouter()

const back = () => {
    router.back()
}

const emit = defineEmits(['submit', 'change'])
const props = withDefaults(defineProps<CustomFormProps>(), {})

const title = computed(() => {
    return props.title
})

const defaultFormList = ref(cloneDeep(props.formList))
const getFormList = ref(cloneDeep(props.formList))
watch(() => props.formList, () => {
    getFormList.value = cloneDeep(props.formList)
    defaultFormList.value = cloneDeep(props.formList)
}, { deep: true })

const addFormItem = (formItem: CustomFormItem) => {
    unref(formItem).children?.push({ type: formItem.subItemType, id: nanoid() })
    switch (formItem.subItemType) {
        case 'range':
            formState[formItem.key].push({
                startTime: '',
                endTime: '',
                fee: ''
            })
            break
        case 'input':
            formState[formItem.key].push('')
            break
        case 'distanceRule':
            formState[formItem.key].push({
                startDistance: '1',
                endDistance: '3',
                distance: '1',
                fee: '1'
            })
            break
        case 'weightRules':
            formState[formItem.key].push({
                startDistance: '1',
                endDistance: '3',
                weight: '1',
                fee: '1'
            })
            break
        case 'timePeriodRules':
            formState[formItem.key].push({
                startTime: dayjs('00:00', 'HH:mm'),
                endTime: dayjs('07:00', 'HH:mm'),
                fee: '1'
            })
            break
        case 'weightLabel':
            formState[formItem.key].push({
                start: '0',
                end: '1',
                state: '1',
                name: ''
            })
            break
        case 'discountCouponRules':
            formState[formItem.key].push({
                coupon: '1',
                probability: '0',
            })
    }
}

const removeFormItem = (formItem: CustomFormItem, index: number) => {
    unref(formItem).children?.splice(index, 1)
    formState[formItem.key].splice(index, 1)
}

const formState = reactive<CustomFormState>({})

const initState = () => {
    let list = cloneDeep(unref(getFormList))
    list.forEach((item: CustomFormItem) => {
        if (item.type === 'submit') return
        if (item.type === 'free' || item.type === 'upload') {
            formState[item.key] = []
            return
        }
        if (item.type === 'drawSome') {
            formState[item.key] = {
                helpMeDeliverIt: 0.00,
                helpMeRetrieveIt: 0.00,
                helpMeBuyIt: 0.00
            }
            return
        }
        if (item.type === 'discount') {
            formState[item.key] = {
                discountAmount: '0',
                qualifiedAmount: '0'
            }
            return
        }
        formState[item.key] = item.value || ''
    })
}

watch(() => props.formList, () => {
    initState()
}, { immediate: true })

const FormRef = ref<any>()

const change = (formItem: CustomFormItem) => {
    emit('change', unref(formItem))
}

const onSubmit = () => {
    FormRef.value.validateFields().then((res: any) => {
        emit('submit', unref(formState))
        getFormList.value = defaultFormList.value
        initState()
    }).catch((reject: any) => {
        message.error('表单填写有误');
    })
}
</script>

<style scoped lang="scss">
:deep(.ant-form) {

    .ant-form-item,
    .ant-form-item-rest {
        width: 450px;

        .ant-form-item-row {
            display: block;
        }

        .ant-form-item-label {
            margin-bottom: 10px;
        }
    }
}
</style>